<template>
  <view class="cartBox">
    <view v-if="cart.length === 0" class="empty">购物车空空如也~</view>
    <view v-else>
      <view class="toolBar">
        <checkbox :checked="allChecked" @click="toggleAll">全选</checkbox>
      </view>
      <view class="item" v-for="(good, idx) in cart" :key="good.id">
        <checkbox
          class="cartCheckbox"
          :checked="good.checked"
          @click="toggleOne(idx)"
        />
        <image class="cartImg" :src="good.goods_icon" mode="aspectFill" />
        <view class="info">
          <text class="cartName">{{ good.goods_desc }}</text>
          <text class="cartPrice">￥{{ good.goods_price }}</text>
          <u-number-box
            v-model="good.num"
            :min="1"
            longPress=true
            disabledInput=true
            @change="(e) => changeNum(e, good.num, good.goods_id)"
          />
        </view>
      </view>
	  <view class="toolBar">
        <text class="total">合计：￥{{ totalPrice.toFixed(2) }}</text>
        <button class="btn" @click="toDelete">删除</button>
        <button class="btn primary" @click="toSettlement">结算</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { addCart,getCarts, deleteCart } from '../../api/api'
import { onShow } from '@dcloudio/uni-app'

const cart = ref([])

async function getCart() {
  const { data } = await getCarts({
    username: uni.getStorageSync('loginUserName')
  }, { showLoading: false })
  cart.value = data.map(item => ({
    ...item,
    checked: false,
    num: item.car_num
  }))
}

const allChecked = computed(() => cart.value.length && cart.value.every(g => g.checked))
const totalPrice = computed(() =>
  cart.value
    .filter(g => g.checked)
    .reduce((sum, g) => sum + g.goods_price * g.num, 0)
)

function toggleAll() {
  const next = !allChecked.value
  cart.value.forEach(g => (g.checked = next))
}
function toggleOne(idx) {
  cart.value[idx].checked = !cart.value[idx].checked
}

function changeNum(e, num, goodId) {
  addCart({
    username: uni.getStorageSync('loginUserName'),
		goods_id: goodId,
    quantity: e.value - num
  }, { showLoading: false }).then(res => {
    if (res.code === 200) {
      uni.showToast({ title: '修改成功', icon: 'none' })
      getCart()
    } else {
      uni.showToast({ title: res.data.message || '修改失败', icon: 'none' })
    }
  }).catch(err => {
    uni.showToast({ title: err.data.message || '修改失败', icon: 'none' })
    console.log(goodId)
  })
}

// function changeNum(e, num, goodId) {
//   uni.request({
//     url: `http://47.121.118.187:7788/cart/addCart?username=${uni.getStorageSync('loginUserName')}&goods_id=${goodId}&quantity=${e.value - num}`
//     method: 'GET'
//     timeout: 5000
//     success: (res) => {
//       if (res.data.code === 200) {
//         uni.showToast({ title: '修改成功', icon: 'none' })
//         getCart()
//       } else {
//         uni.showToast({ title: res.data.message || '修改失败', icon: 'none' })
//       }
//     },
//     fail: (err) => {
//       uni.showToast({ title: err.data.message || '修改失败', icon: 'none' })
//       console.log(goodId)
//     }
//   })
// }



function toDelete() {
	const ids = cart.value.filter(g => g.checked).map(g => g.id)
	if (ids.length === 0) {
		uni.showToast({ title: '请选择要删除的商品', icon: 'none' })
		return
	}
	uni.showModal({
		title: '确认删除',
		content: '确认删除所选商品？',
		success: async (res) => {
			if (res.confirm) {
				try {
					const res = await deleteCart({
            username: uni.getStorageSync('loginUserName'),
            ids
          })
					if (res.code === 200) {
						uni.showToast({ title: '删除成功', icon: 'none' })
						getCart()
					} else {
						uni.showToast({ title: res.data.message || '删除失败', icon: 'none' })
					}
				} catch (err) {
					uni.showToast({ title: err.data.message || '删除失败', icon: 'none' })
				}
			}
		}
	})
}

function toSettlement() {
  const ids = cart.value.filter(g => g.checked).map(g => g.id)
	if (ids.length === 0) {
		uni.showToast({ title: '请选择要结算的商品', icon: 'none' })
		return
	}
  uni.showModal({
		title: '确认结算',
		content: `您本次结算共${cart.value.filter(g => g.checked).reduce((sum, g) => sum + g.num, 0)}件商品，总金额${(totalPrice.value).toFixed(2)}元，是否确认结算？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					const res = await deleteCart({
            username: uni.getStorageSync('loginUserName'),
            ids
          })
					if (res.code === 200) {
						uni.showToast({ title: '结算成功', icon: 'none' })
						getCart()
					} else {
						uni.showToast({ title: res.data.message || '结算失败', icon: 'none' })
					}
				} catch (err) {
					uni.showToast({ title: err.data.message || '结算失败', icon: 'none' })
				}
			}
		}
	})
}

onShow(() => {
  getCart()
})
</script>

<style lang="scss" scoped>
.cartBox {
  padding: 20rpx;
  min-height: 100vh;
  background: #f5f5f5;
  .empty {
    text-align: center;
    margin-top: 200rpx;
    color: #999;
  }
  .toolBar {
    display: flex;
    align-items: center;
    background: #fff;
    padding: 20rpx;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    .total {
      flex: 1;
      font-weight: 600;
      color: #ff2d46;
    }
    .btn {
      margin-left: 16rpx;
      font-size: 26rpx;
      padding: 8rpx 30rpx;
      border-radius: 0rpx;
      &.primary {
        background: linear-gradient(90deg, #ff6a6a, #ff2d46);
        color: #fff;
      }
    }
  }
  .item {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    padding: 20rpx;
    .cartImg {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin: 0 20rpx;
    }
    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      .cartName {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 8rpx;
        line-height: 1.4;
      }
      .cartPrice {
        font-size: 30rpx;
        color: #ff2d46;
        margin-bottom: 12rpx;
      }
    }
  }
}
</style>